﻿using Away.Jobs.Services.Implements;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Quartz.AspNetCore;
using System.Collections.Specialized;

namespace Away.Jobs;

public static class HostBuilderExtensions
{
    /// <summary>
    /// 添加定时任务模块
    /// </summary>
    /// <param name="builder"></param>
    public static void AddJobs(this IHostBuilder builder)
    {
        builder.ConfigureServices((host, services) =>
        {
            var conn = host.Configuration.GetConnectionString("MySql");
            var ver = ServerVersion.Parse("8.0.26");
            services.AddDbContext<JobsDbContext>(o => o.UseMySql(conn, ver));
            services.AddHostedService<InitTablesHostService<JobsDbContext>>();

            var key = "QuartzSettings";
            var config = host.Configuration.GetSection(key).AsEnumerable();
            var properties = new NameValueCollection();
            foreach (var (k, v) in config)
            {
                if (k == key)
                {
                    continue;
                }
                properties.Add(k.Replace($"{key}:", ""), v);
            }
            services.AddQuartz(properties, o => o.AddAwayJobs());
            services.AddQuartzServer(options =>
            {
                options.WaitForJobsToComplete = false;
            });
            services.AddScoped<ITriggerService, TriggerService>();
            services.AddScoped<IJobService, JobService>();
        });
    }
}
